#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2023/4/7 20:59
# @Author  : WJQ
# @Site    : 
# @File    : form_handler.py.py
# @Software: PyCharm
import time
from appium.webdriver.webelement import WebElement
import random
import string
from appium.webdriver.common.appiumby import AppiumBy
from typing import List

from browser.driver_zfb import DriverHandlerZfb
from browser.page import PageHandler
from crawler.modules.click_handler import ClickHandler
from utils.common import CrawlerLogger
from conf import INPUT_VALUES

class FormHandler:
    def __init__(self, driver_handler):
        self.driver_handler: DriverHandlerZfb = driver_handler
        self.submit_button_texts = ['submit', 'search', '确定', '提交', '搜索']

    def fill_inputs(self, input_elements: List[WebElement]) -> None:
        for element in input_elements:
            try:
                if not (element.is_enabled() and element.is_displayed()):
                    continue
                # label = PageHandler.get_label(self.driver_handler, element)
                label = element.get_attribute('text')
                if label != " ":
                    self._fill_element_with_value(element, label)
                else:
                    random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
                    element.clear()
                    element.send_keys(random_string)
            except Exception as e:
                CrawlerLogger.debug(f"[-] Failed to fill input: {e}")

    def _fill_element_with_value(self, element: WebElement, label: str) -> None:
        for key, value in INPUT_VALUES.items():
            if key in label:
                element.clear()
                element.send_keys(INPUT_VALUES[key])
                return
        # random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
        element.clear()
        element.send_keys(label)

    def find_and_click_submit_button(self, buttons: List) -> None:
        for button in buttons:
            button_text = button.text.lower()
            if any(submit_text.lower() in button_text for submit_text in self.submit_button_texts):
                ClickHandler.safe_click(self.driver_handler.driver, button, 'Native APP')
                break

    def handle_form_elements(self):
        input_xpath = 'android.widget.EditText'
        input_elements = PageHandler.safe_find_elements(self.driver_handler.driver, AppiumBy.CLASS_NAME, input_xpath, timeout=1)
        self.fill_inputs(input_elements)
        return input_elements



        # 查找按钮并尝试点击提交按钮
        # button_xpath = 'android.widget.Button'
        # button_elements = self.driver_handler.driver.find_elements(AppiumBy.CLASS_NAME, button_xpath)
        # self.find_and_click_submit_button(button_elements)

    def handle_login_form(self):
        """
        handle login form
        :return:
        """

        button = PageHandler.safe_find_element(self.driver_handler.driver, AppiumBy.XPATH, "//*[@text='搜索指定内容']")
        if button:
            ClickHandler.safe_click(self.driver_handler.driver, button, 'native')
            close_btn = PageHandler.safe_find_element(self.driver_handler.driver, AppiumBy.ID, "com.tencent.mm:id/iq6")
            if close_btn:
                ClickHandler.safe_click(self.driver_handler.driver, close_btn, 'native')
                CrawlerLogger.info(f"[+] 登录成功")
                time.sleep(1)
                return

